package com.yb.auth.core.handler;

import com.alibaba.fastjson2.JSONObject;
import com.yb.core.bean.Resp;
import com.yb.core.constant.HttpConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/13 20:30
 * FileName: AuthEntryPoint
 * Description:
 */
@Slf4j
public class AuthEntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        log.error("{}",authException);
        if(authException instanceof InsufficientAuthenticationException){
            response.getWriter().write(JSONObject.toJSONString(Resp.ok(HttpConstant.Response.NOT_LOGIN)));
        }

        if(authException instanceof UsernameNotFoundException){
            response.getWriter().write(JSONObject.toJSONString(Resp.ok(HttpConstant.Response.USER_NOT_EXISTS)));
        }

    }
}
